package com.dao.impl;

import com.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.dao.MessageDAO;
import com.rev.Action;
import com.rev.Automaticintervention;
import com.rev.Message;
import com.rev.MessageHome;
import com.rev.SourceHome;
import com.rev.Sourcetype;
import com.rev.SourcetypeHome;

public class MessageDAOImpl implements MessageDAO{
	
	private MessageHome mh = new MessageHome(); 
	private SourceHome sh = new SourceHome(); 
	private SourcetypeHome sth = new SourcetypeHome();

	public boolean insert(Message message) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			if(sth.findById(message.getSource().getSourcetype().getIdSourceType()) == null)
				sth.attachDirty(message.getSource().getSourcetype());
			if(sh.findById(message.getSource().getIdSource()) == null)
				sh.attachDirty(message.getSource());
			mh.attachDirty(message);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {}
		return false;
	}

	public boolean update(Message message) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			mh.attachDirty(message);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public boolean delete(Message message) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction  transaction = session.beginTransaction();
			mh.delete(message);
			transaction.commit();
			session.close();
			return true;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return false;
	}

	public Message findById(int id) {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			Message s = mh.findById(id);
			session.getTransaction().commit();
			session.close();
			return s;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public List<Automaticintervention> findAutomaticInterventions(
			Message message) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public List<Message> findAll() {

		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			List list = mh.findByExample(new Message());
			session.getTransaction().commit();
			session.close();
			return list;
		} catch (Exception e) {
		}
		return null;
	}

}
